﻿using Newtonsoft.Json;
using PublicLib.WebLib;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DataServerHntjControl
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        System.Windows.Threading.DispatcherTimer tm = new System.Windows.Threading.DispatcherTimer();
        //ServiceHost host;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            LoadData();
            tm.Interval = new TimeSpan(0, 0, 3);
            tm.Tick += Tm_Tick;
            //try
            //{
            //    ////创建宿主的基地址
            //    //Uri baseAddress = new Uri("http://localhost:8088/ServiceRequest");
            //    ////创建宿主
            //    //host = new ServiceHost(typeof(InquireService.ServiceRequest), baseAddress);
            //    ////向宿主中添加终结点
            //    //ServiceEndpoint endpoint =
            //    //    host.AddServiceEndpoint(typeof(InquireService.IServiceRequest), new WebHttpBinding(), baseAddress);
            //    ////将HttpGetEnabled属性设置为true
            //    //WebHttpBehavior httpBehavior = new WebHttpBehavior();
            //    //endpoint.Behaviors.Add(httpBehavior);
            //    ////打开宿主
            //    //host.Open();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.ToString());
            //}
        }

        private void Tm_Tick(object sender, EventArgs e)
        {
            CheckIsBusy(new HttpOperation(textUrl.Text));
        }

        private void LoadData()
        {
            textFromTime.Text = Properties.Settings.Default.fromtime;
            textToTime.Text = Properties.Settings.Default.totime;
            textUrl.Text = Properties.Settings.Default.url;
            textUser.Text = Properties.Settings.Default.userid;
            textStage.Text = Properties.Settings.Default.stage;
            switch (Properties.Settings.Default.requestType)
            {
                case "document":
                    buttonDocument.IsChecked = true;
                    break;
                case "tree":
                    buttonTree.IsChecked = true;
                    break;
                case "his":
                    buttonHis.IsChecked = true;
                    break;
                default:
                    buttonDocument.IsChecked = true;
                    break;
            }
        }

        private void SaveData()
        {
            Properties.Settings.Default.fromtime = textFromTime.Text;
            Properties.Settings.Default.totime = textToTime.Text;
            Properties.Settings.Default.url = textUrl.Text;
            Properties.Settings.Default.userid = textUser.Text;
            Properties.Settings.Default.stage = textStage.Text;
            if (buttonDocument.IsChecked == true)
                Properties.Settings.Default.requestType = "document";
            else if (buttonTree.IsChecked == true)
                Properties.Settings.Default.requestType = "tree";
            else if (buttonHis.IsChecked == true)
                Properties.Settings.Default.requestType = "his";
            Properties.Settings.Default.Save();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            SaveData();
        }
        private void buttonSend_Click(object sender, RoutedEventArgs e)
        {
            SaveData();
            HttpOperation http = new HttpOperation(textUrl.Text);
            string receive = string.Empty, send = string.Empty;
            if (CheckIsBusy(http))
            {
                MessageBox.Show("远端服务器正在处理请求");
                resultTextReceive.Text = receive;
                return;
            }
            if (buttonDocument.IsChecked == true)
            {
                DataModel.Send.HeaderBase frame = new DataModel.Send.Frame.RequestDocument();
                string sendAddr = "RequestControl/RequestData?user=" + textUser.Text + "&operation=documentStruct";
                receive = sendData(http, frame, sendAddr);
            }
            else if (buttonTree.IsChecked == true)
            {
                DataModel.Send.HeaderBase frame = new DataModel.Send.Frame.RequestTree();
                string sendAddr = "RequestControl/RequestData?user=" + textUser.Text + "&operation=treeStruct";
                receive = sendData(http, frame, sendAddr);
            }
            else if (buttonHis.IsChecked == true)
            {
                DataModel.Send.Frame.RequestHisdata frame = new DataModel.Send.Frame.RequestHisdata();
                DateTime temp;
                if (!DateTime.TryParse(this.textFromTime.Text, out temp) || !DateTime.TryParse(this.textToTime.Text, out temp))
                {
                    MessageBox.Show("时间格式错误！请修正");
                    return;
                }
                frame.Data.Fromtime = this.textFromTime.Text;
                frame.Data.Totime = this.textToTime.Text;
                string sendAddr = "RequestControl/RequestData?user=" + textUser.Text + "&operation=hisdata";
                receive = sendData(http, frame, sendAddr);
            }
            resultTextReceive.Text = receive;
            resultTextSend.Text = send;
            buttonSend.IsEnabled = false;
            tm.Start();
        }

        private string sendData(HttpOperation http, DataModel.Send.HeaderBase frame, string sendAddr)
        {
            string receive;
            frame.User = textUser.Text;
            frame.Code = DataModel.PublicModel.Typedef.ErrorType.OK;
            frame.Message = string.Empty;
            frame.Stage = textStage.Text;
            using (MemoryStream ms = new MemoryStream())
            {
                TextWriter tr = new StreamWriter(ms);
                JsonSerializer.CreateDefault().Serialize(tr, frame);
                tr.Flush();
                ms.Position = 0;
                receive = http.Post(new StreamReader(ms).ReadToEnd(), sendAddr);
            }

            return receive;
        }

        private bool CheckIsBusy(HttpOperation http)
        {
            string check = http.Get("RequestControl/CheckRunning?user=" + textUser.Text + "&stage=" + textStage.Text);
            Debug.WriteLine(check);
            if (!string.IsNullOrWhiteSpace(check))
            {
                buttonSend.IsEnabled = false;
                tm.Start();
                return true;
            }
            else
            {
                buttonSend.IsEnabled = true;
                tm.Stop();
                return false;
            }
        }

        private void text_TextChanged(object sender, TextChangedEventArgs e)
        {
            buttonSend.IsEnabled = true;
            tm.Stop();
        }

        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            if (SimpleWPFWindows.CheckPasswordWindow.Show("请输入密码", "123456") == true)
            {
                HttpOperation http = new HttpOperation(textUrl.Text);
                string res = http.Post("{\"stage\":\"" +textStage.Text + "\",\"password\":\"funyammy\"}", "RequestControl/CancelRunning?user=" + textUser.Text);
                if (res == "OK")
                {
                    buttonSend.IsEnabled = true;
                    tm.Stop();
                }                    
            }
        }
    }
}
